import React from 'react'
import ReactECharts from 'echarts-for-react'
import type { EChartsOption } from 'echarts'

export interface PieChartData {
  name: string
  value: number
  color?: string
}

export interface PieChartProps {
  data: PieChartData[]
  height?: number | string
  title?: string
  showPercentage?: boolean
}

/**
 * 饼图组件
 * 用于占比数据展示
 */
const PieChart: React.FC<PieChartProps> = ({
  data,
  height = 400,
  title,
  showPercentage = true
}) => {
  const option: EChartsOption = {
    title: title ? {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    } : undefined,
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        return `<div>
          <div style="font-weight: bold; margin-bottom: 4px;">${params.name}</div>
          <div>数值: ${params.value.toLocaleString()}</div>
          <div>占比: ${params.percent}%</div>
        </div>`
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: data.map(item => item.name)
    },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['40%', '50%'],
      avoidLabelOverlap: true,
      itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: showPercentage,
        formatter: '{b}: {d}%'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      data: data.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: item.color ? {
          color: item.color
        } : undefined
      }))
    }]
  }

  return (
    <ReactECharts
      option={option}
      style={{ height, width: '100%' }}
      opts={{ renderer: 'canvas' }}
    />
  )
}

export default PieChart
